import { createBobPlugin } from '../vite.config.js';
import chokidar from 'chokidar';
import path from 'path';
import fs from 'fs';

const IGNORED_FILES = [
    'info.json',  // 忽略自动生成的版本文件
    '.DS_Store',  // macOS 系统文件
    'node_modules',
    /\.log$/
];

const watcher = chokidar.watch('src', {
    persistent: true,
    ignoreInitial: false,
    ignored: [
        /(^|[\/\\])\../, // 忽略隐藏文件
        ...IGNORED_FILES
    ]
});

// 防抖函数，避免频繁触发
function debounce(func, wait) {
    let timeout;
    return function(...args) {
        const context = this;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
    };
}

const debouncedBuild = debounce(async () => {
    console.log('\n\n--------------------------------\n','🔄 重新构建开发版本');
    await createBobPlugin(true);
}, 300);

watcher.on('all', async (event, filePath) => {
    // 获取相对路径
    const relativePath = path.relative(process.cwd(), filePath);
    
    // 检查是否为需要忽略的文件
    const shouldIgnore = IGNORED_FILES.some(pattern => {
        if (pattern instanceof RegExp) {
            return pattern.test(relativePath);
        }
        return relativePath.includes(pattern);
    });

    if (shouldIgnore) {
        console.log('\n\n--------------------------------\n',` 忽略文件变更: ${relativePath}`);
        return;
    }

    // 只处理 src 目录下的文件变更
    if (path.resolve(filePath).startsWith(path.resolve('src'))) {
        console.log('\n\n--------------------------------\n',` ${event} detected in ${relativePath}`);
        debouncedBuild();
    }
});